package com.my.java.bookman.service;

import com.my.java.bookman.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import sun.misc.CEFormatException;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 *  自定义UserService
 */
@Service
public class UserDetailServiceImpl<T extends User> implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

            User user = userService.getUserByUsername(username);
            if (user ==null) {
                throw new UsernameNotFoundException("用户："+username+"不存在！");
            }

            //用户权限
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();

            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);

    }

    public void add(User user) throws CEFormatException {
        String name=user.getName();
        String sex=user.getSex();
        String username=user.getUsername();
        String password=user.getPassword();
        if (name==null){
            throw new CEFormatException("姓名不能为空");

        }

        if (sex=="0"){
            throw new CEFormatException("性别不能为空");
        }

        if (username==null){
            throw new CEFormatException("用户名不能为空");
        }

        if (password==null){
            throw new CEFormatException("密码不能为空");
        }
         String salt= UUID.randomUUID().toString().toUpperCase(Locale.ROOT);
         user.setName(name);
         user.setSex(sex);
         user.setUsername(username);
         user.setPassword(password);
        System.out.println("用户"+user+"注册成功");
    }

}
